<template>
  <div class="mind-container">
    <template v-if="show">
      <Toolbar :mind-map-data="mindMapData" :other-info="otherInfo" />
      <Edit v-if="mindMapData" ref="Edit" v-model="mindMapData" :mode="modeFlag" :is-lock="isLock" :time="otherInfo.updateTime" />
      <el-dialog :title="$t('选择分享用户')" :visible.sync="shareOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body width="30%">
        <el-form
          ref="form"
          :model="shareForm"
          :rules="shareRules"
          label-width="120px"
          class="dataForm"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('分享用户')" prop="userIdList">
                <UserSelect
                  v-model="shareForm.userIdList"
                  :multiple="true"
                  :placeholder="$t('分享用户')"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="shareConfirmHandle">{{ $t('确定') }}</el-button>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import Toolbar from './components/Toolbar'
import Edit from './components/Edit'
import { mapActions } from 'vuex'
import { getData, getLocalConfig } from '@/components/SimpleMindMap/api'
import { saveDealEstateMapJson, getDealEstateMap, shareData } from '@/api/deal/map/dealEstateMap'
export default {
  name: 'Index',
  components: {
    Toolbar,
    Edit
  },
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: 'edit'
    },
    isLock: {
      type: String,
      default: 'N'
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    },
    otherInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      mapId: this.$route.query.id,
      show: false,
      isZenMode: false,
      modeFlag: this.isLock && this.isLock === 'Y' ? 'readonly' : this.mode,
      userId: this.$store.state.user.userId,
      form: {
        id: this.$route.query.id
      },
      shareForm: {
        userIdList: []
      },
      mindMapData: undefined,
      mindMapDataInit: {
        mindMapData: {
            'root': {
                'data': {
                    'text': '根节点',
                    'expand': true,
                    'isActive': false
                }
            },
            'theme': {
                'template': 'themeDiy',
                'config': {}
            },
            'layout': 'logicalStructure',
            'config': {},
            'view': {
                'transform': {
                    'scaleX': 1,
                    'scaleY': 1,
                    'shear': 0,
                    'rotate': 0,
                    'translateX': -215,
                    'translateY': 9,
                    'originX': 0,
                    'originY': 0,
                    'a': 1,
                    'b': 0,
                    'c': 0,
                    'd': 1,
                    'e': -215,
                    'f': 9
                },
                'state': {
                    'scale': 1,
                    'x': -215,
                    'y': 9,
                    'sx': -212,
                    'sy': 8
                }
            }
        }
      },
      shareRules: {
        userIdList: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
      },
      shareOpen: false
    }
  },
  computed: {
  },
  async created() {
    this.$bus.$on('saveData', () => {
      // 手动保存数据
      this.submitForm('save')
    })
    this.$bus.$on('autoSaveData', () => {
      // 自动保存数据
      this.submitForm('auto')
    })
    this.$bus.$on('shareData', () => {
      // 分享
      this.shareOpen = true
    })
    // 如果锁定则提示
    if (this.isLock === 'Y' && this.mode === 'edit') {
      var editInfo = ''
      if (this.otherInfo && this.otherInfo.lockUserName) {
        editInfo = this.otherInfo.lockUserName + '正在编辑。'
      }

      this.$notify({
          title: '锁定',
          message: '编辑状态已锁定！' + editInfo,
          type: 'warning',
          duration: 0
        })
    }
    if (this.data) {
      this.mindMapData = this.data
    } else {
      this.mindMapData = this.mindMapDataInit.mindMapData
    }
    console.log(this.mindMapData)
    await this.initLocalConfig()
    const loading = this.$loading({
      lock: true,
      text: '正在加载，请稍后...'
    })
    // this.init()
    await this.getUserMindMapData()
    this.show = true
    loading.close()
  },
  beforeDestroy() {
    var data = localStorage.getItem('SIMPLE_MIND_MAP_DATA')
    this.$emit('input', data)
    localStorage.setItem('SIMPLE_MIND_MAP_DATA', getData())
  },
  methods: {
    ...mapActions(['getUserMindMapData']),
    setLocalConfig(payLoad) {
      this.$store.commit('setLocalConfig', payLoad)
    },

    /**
     * @Desc: 初始化本地配置
     */
    initLocalConfig() {
      const config = getLocalConfig()
      if (config) {
        this.setLocalConfig({
          ...this.$store.state.localConfig,
          ...config
        })
      }
    },
    // 初始化数据
    init() {
      if (this.mapId) {
          getDealEstateMap(this.mapId).then(response => {
              this.form = response.data
              // this.getUserMindMapData(JSON.parse(response.data.dataJson))
              // this.$refs.Edit.mindMap.setData(JSON.parse(response.data.dataJson))
              this.mindMapDataInit.mindMapData = JSON.parse(response.data.dataJson)
              this.$forceUpdate()
          }).catch(() => {
          })
      }
    },
    /** 提交按钮 */
    submitForm(type) {
        // 获取json串
        this.form.dataJson = JSON.stringify(getData())
        saveDealEstateMapJson(this.form).then(response => {
            if (response.code === 200) {
              if (type && type !== 'auto') {
                this.msgSuccess(this.$t('保存成功'))
              }
              this.otherInfo.updateTime = this.parseTime(response.data.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')
            } else {
                this.msgError(response.msg)
            }
        })
    },
    shareConfirmHandle() {
      this.shareForm.id = this.mapId
      shareData(this.shareForm).then(response => {
            if (response.code === 200) {
                this.msgSuccess(this.$t('分享成功'))
                this.shareOpen = false
            } else {
                this.msgError(response.msg)
            }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.mind-container {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}
</style>
